<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="固件名称" prop="firmwareName">
        <el-input
          v-model="queryParams.firmwareName"
          placeholder="请输入固件名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="固件版本" prop="firmwareVersion">
        <el-input
          v-model="queryParams.firmwareVersion"
          placeholder="请输入固件版本"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="firmwareMark">
        <el-input
          v-model="queryParams.firmwareMark"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" prop="firmwareDate">
        <el-date-picker clearable size="small"
          v-model="queryParams.firmwareDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bus:firmware:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bus:firmware:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bus:firmware:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bus:firmware:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="firmwareList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="firmwareId" />
      <el-table-column label="固件名称" align="center" prop="firmwareName" />
      <el-table-column label="固件版本" align="center" prop="firmwareVersion" />
      <!-- <el-table-column label="固件地址" align="center" prop="firmwareUrl" /> -->
       <el-table-column label="固件地址" align="center" prop="firmwareUrl"  width="280">
        <template slot-scope="scope"> {{ scope.row.firmwareUrl }}
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="scope.row.firmwareUrl" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
        </template>
      </el-table-column>

      
      <el-table-column label="关联设备" align="center" prop="firmwareTo" />
      <el-table-column label="备注" align="center" prop="firmwareMark" />
      <!-- <el-table-column label="状态" align="center" prop="firmwareStatus" /> -->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">{{
          scope.row.firmwareStatus == "0" ? "启用" : "禁用"
        }}</template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="firmwareDate" />
      <!-- <el-table-column label="更新时间" align="center" prop="firmwareDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.firmwareDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bus:firmware:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bus:firmware:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改固件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="固件名称" prop="firmwareName">
          <el-input v-model="form.firmwareName" placeholder="请输入固件名称" :disabled="true"/>
        </el-form-item>
        <el-form-item label="固件版本" prop="firmwareVersion">
          <el-input v-model="form.firmwareVersion" placeholder="请输入固件版本" />
        </el-form-item>
        <el-form-item label="关联设备" prop="firmwareTo">
          <el-input v-model="form.firmwareTo" placeholder="请输入关联设备" />
        </el-form-item>
        <el-form-item label="备注" prop="firmwareMark">
          <el-input v-model="form.firmwareMark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

        <el-upload
          class="upload-demo"
          drag
          :action="actionurl"
          :before-upload="handleBeforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :headers="headers"
          :data="form"
          accept=".bin"
          :file-list="fileList"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传bin文件，且不超过5Mb</div>
        </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFirmware, getFirmware, delFirmware, addFirmware, updateFirmware } from "@/views/firmware/firmware";
import { getToken } from "@/utils/auth";

export default {
  name: "Firmware",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组中 固件文件名称
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 固件信息表格数据
      firmwareList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        firmwareName: null,
        firmwareVersion: null,
        firmwareUrl: null,
        firmwareTo: null,
        firmwareMark: null,
        firmwareStatus: null,
        firmwareDate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        firmwareName: [{ required: true, message: "固件名称不能为空", trigger: "blur" },],
        firmwareVersion: [{ required: true, message: "固件版本不能为空", trigger: "blur" },],
      },
       
       // 上传固件文件大小限制(MB)
      fileList: [],
      fileSize:5,
      actionurl: process.env.VUE_APP_PORT + "file/firmwarefile/upload", // 上传固件文件的服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 固件文件上传
    };
  },
  created() {
    this.getList();
  },
  methods: {

    /** 查询固件信息列表 */
    getList() {
      this.loading = true;
      listFirmware(this.queryParams).then(response => {
        this.firmwareList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        firmwareId: null,
        firmwareName: null,
        firmwareVersion: null,
        firmwareUrl: null,
        firmwareTo: null,
        firmwareMark: null,
        firmwareStatus: "0",
        firmwareDate: null
      };
      this.resetForm("form");
      this.fileList=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.firmwareId)
      this.names = selection.map(item => item.firmwareName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加固件信息";
      this.form.firmwareName= this.uuid2(16, 16);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const firmwareId = row.firmwareId || this.ids
      getFirmware(firmwareId).then(response => {
        this.form = response.data.data;
        this.open = true;
        this.title = "修改固件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form);
          if (this.form.firmwareId != null) {
            updateFirmware(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFirmware(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const firmwareIds = row.firmwareId || this.ids;
      const firmwareNames = row.firmwareName || this.names;
      this.$confirm('是否确认删除固件信息编号为"' + firmwareIds + '"的数据项？').then(function() {
        return delFirmware(firmwareIds,firmwareNames);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bus/firmware/export', {
        ...this.queryParams
      }, `firmware_${new Date().getTime()}.xlsx`)
    },
    
    
    // 上传bin文件前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    handleUploadSuccess(res, file) {
      
      // 如果上传成功
      if (res.code == 200) {

        //   res.url为服务器返回的图片地址
         this.form.firmwareUrl = res.data[0].url;
         this.$message({ message: res.msg, type: "success" });

      } else {
        this.$message.error("固件上传失败");
      }
    },
    handleUploadError() {
      this.$message.error("固件上传失败");
    },

    /** 复制代码成功 */
    clipboardSuccess(){
      this.$message.success("复制成功");
    },

  }
};
</script>

<style scoped>

 .upload-demo {
    text-align: center;
 }
</style>
